<template>
    <a-card :bordered="false" class="card-area">
        <div :class="advanced ? 'search' : null">
            <!-- 搜索区域 -->
            <a-form layout="horizontal">
                <div :class="advanced ? null : 'fold'">
                    <a-row>
                        <a-col :md="12" :sm="24">
                            <a-form-item label="法人行" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
                                <a-select v-if="this.user.admin" mode="default" :allowClear="true" style="width: 100%"
                                    @change="handleInstChange" v-model="queryParams.instId">
                                    <a-select-option v-for="r in instIdData" :key="r.label">{{ r.label }}-{{ r.value }}
                                    </a-select-option>
                                </a-select>
                                <a-input v-if="!this.user.admin" v-model="queryParams.instId" :value="this.user.instId"
                                    :disabled="true" />
                            </a-form-item>
                        </a-col>
                        <a-col :md="12" :sm="24" v-show="queryParams.instId != ''">
                            <a-form-item label="机构状态" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
                                <a-select mode="default" v-model="queryParams.orgStatus" :allowClear="true"
                                    style="width: 100%">
                                    <a-select-option key="01">正式</a-select-option>
                                    <a-select-option key="03">已注销</a-select-option>
                                </a-select>
                                <!-- <a-select mode="default" v-model="queryParams.userStatus" :allowClear="true"
                                    style="width: 100%">
                                    <a-select-option key="00">正常</a-select-option>
                                    <a-select-option key="01">注销</a-select-option>
                                    <a-select-option key="02">冻结</a-select-option>
                                </a-select> -->
                            </a-form-item>
                        </a-col>
                        <a-col :md="12" :sm="24" v-show="queryParams.instId != ''">
                            <a-form-item label="机构类型" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
                                <a-select mode="default" :allowClear="true" style="width: 100%"
                                    v-model="queryParams.orgType">
                                    <a-select-option key="00" selected>银行机构</a-select-option>
                                    <a-select-option key="01">代理机构虚拟机构</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </div>
                <div style="text-align: center;" v-show="queryParams.instId != ''">
                    <a-button type="primary" @click="search">查询</a-button>
                    <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                </div>
            </a-form>
        </div>
        <div v-show="queryParams.instId != ''">
            <div class="operator">

                <a-button v-hasPermission="['org:add']" ghost type="primary" @click="createOrg(null)">新增</a-button>
                <a-button v-hasPermission="['org:delete']" @click="batchDelete">注销</a-button>
                <a-dropdown v-hasPermission="['org:export']">
                    <a-menu slot="overlay">
                        <a-menu-item key="export-data" @click="exprotExccel">导出Excel</a-menu-item>
                    </a-menu>
                    <a-button>
                        更多操作
                        <a-icon type="down" />
                    </a-button>
                </a-dropdown>
            </div>
            <!-- 表格区域 -->
            <a-table :columns="columns" :rowKey="record => record.id" :dataSource="dataSource" :pagination="pagination"
                :loading="loading" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                @change="handleTableChange" :scroll="{ x: 1500 }">
                <template v-if="text" slot="icon" slot-scope="text, record">
                    <a-icon :type="text" />
                </template>
                <template slot="operation" slot-scope="text, record">
                    <a-icon v-hasPermission="['org:update']" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
                        @click="edit(record)" title="修改"></a-icon>
                    <a-icon v-hasPermission="['org:add']" type="plus-circle" theme="twoTone" twoToneColor="#4a9ff5"
                        @click="createOrg(record)" title="添加下属机构"></a-icon>
                    <a-badge v-hasNoPermission="['org:update']" status="warning" text="无权限"></a-badge>
                </template>
            </a-table>
        </div>
        <!-- 新增菜单 -->
        <org-add @close="handleOrgAddClose" @success="handleOrgAddSuccess" :orgAddVisiable="orgAddVisiable"
            :orgParent="orgParent" :orgInstId="queryParams.instId">
        </org-add>
        <!-- 修改菜单 -->
        <org-edit ref="orgEdit" @close="handleOrgEditClose" @success="handleOrgEditSuccess"
            :orgEditVisiable="orgEditVisiable" :orgInstId="queryParams.instId">
        </org-edit>
    </a-card>
</template>

<script>
import RangeDate from '@/components/datetime/RangeDate'
import OrgAdd from './OrgAdd'
import OrgEdit from './OrgEdit'
import { mapState } from "vuex"

export default {
    name: 'Org',
    components: { RangeDate, OrgAdd, OrgEdit },
    data() {
        return {
            advanced: false,
            key: +new Date(),
            queryParams: {
                instId: '', orgStatus: ' ', orgType: ' '
            },
            filteredInfo: null,
            dataSource: [],
            selectedRowKeys: [],
            channelTypeData: [],
            pagination: {
                defaultPageSize: 10000000,
                hideOnSinglePage: true,
                indentSize: 100
            },
            loading: false,
            orgAddVisiable: false,
            orgEditVisiable: false,
            buttonAddVisiable: false,
            buttonEditVisiable: false,
            instIdData: [],
            orgParent: {
                id: "",
                orgCode: ""
            }
        }
    },
    computed: {
        ...mapState({
            user: state => state.account.user
        }),
        columns() {
            let { filteredInfo } = this
            filteredInfo = filteredInfo || {}
            return [{
                title: '机构类型',
                dataIndex: 'orgType',
                width: 200,
                fixed: 'left',
                customRender: (text, row, index) => {
                    switch (text) {
                        case '00':
                            return <a-tag color="cyan" > 银行机构 </a-tag>
                        case '01':
                            return <a-tag color="pink" > 代理机构虚拟机构 </a-tag>
                        default:
                            return text
                    }
                },
                // filters: [
                //     { text: '银行机构', value: '00' },
                //     { text: '代理机构虚拟机构', value: '01' }
                // ],
                filterMultiple: false,
                filteredValue: filteredInfo.type || null,
                onFilter: (value, record) => record.type.includes(value)
            }, {
                title: '机构代码',
                dataIndex: 'orgCode',
                width: 200,
                fixed: 'left'
            }, {
                title: '机构名称',
                dataIndex: 'orgName',
                width: 200,
                fixed: 'left'
            }, {
                title: '机构级别',
                dataIndex: 'orgLevel',
                width: 200,
                fixed: 'left',
                customRender: (text, row, index) => {
                    switch (text) {
                        case '00':
                            return <a-tag color="cyan" > 总行 </a-tag>
                        case '01':
                            return <a-tag color="pink" > 分行 </a-tag>
                        case '02':
                            return <a-tag color="cyan" > 支行 </a-tag>
                        case '03':
                            return <a-tag color="pink" > 营业部 / 网点 </a-tag>
                        default:
                            return text
                    }
                },
                // filters: [
                //     { text: '总行', value: '00' },
                //     { text: '分行', value: '01' },
                //     { text: '支行', value: '02' },
                //     { text: '营业部/网点', value: '03' }
                // ],
                filterMultiple: false,
                filteredValue: filteredInfo.type || null,
                onFilter: (value, record) => record.type.includes(value)
            }, {
                title: '状态',
                dataIndex: 'orgStatus',
                width: 200,
                fixed: 'left',
                customRender: (text, row, index) => {
                    switch (text) {
                        case '00':
                            return <a-tag color="pink" > 非正式 </a-tag>
                        case '01':
                            return <a-tag color="cyan" > 正式 </a-tag>
                        case '02':
                            return <a-tag color="pink" > 停用 </a-tag>
                        case '03':
                            return <a-tag color="pink" > 已注销 </a-tag>
                        default:
                            return text
                    }
                },
                // filters: [
                //     { text: '非正式', value: '00' },
                //     { text: '正式', value: '01' },
                //     { text: '停用', value: '02' },
                //     { text: '已注销', value: '03' }
                // ],
                filterMultiple: false,
                filteredValue: filteredInfo.status || null,
                onFilter: (value, record) => record.validStatus.includes(value)
            }, {
                title: '操作',
                dataIndex: 'operation',
                width: 120,
                scopedSlots: { customRender: 'operation' },
                fixed: 'right'
            }]
        }
    },
    mounted() {
        this.$get('admin/upmporg/getInstList').then((r) => {
            this.instIdData = r.data
        })
        if (!this.user.admin) {
            this.handleInstChange(this.user.instId);
        }
    },
    methods: {
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys
        },
        handleInstChange(value) {
            this.queryParams.instId = value;
            if (value != "") {
                this.search();
            }
        },
        handleOrgEditClose() {
            this.orgEditVisiable = false
        },
        handleOrgEditSuccess() {
            this.orgEditVisiable = false
            this.$message.success('修改机构信息成功')
            this.search()
        },
        edit(record) {
            if (record.orgStatus == "03") {
                this.$message.warn('已注销的机构无法编辑')
                return false;
            }
            if (record.orgStatus == "02") {
                this.$message.warn('已停用的机构无法编辑')
                return false;
            }
            this.orgEditVisiable = true
            this.$get('admin/upmporg/detail/' + record.id).then((r) => {
                let data = r.data.data
                console.log(data);
                this.$refs.orgEdit.setFormValues(data)
            })
        },
        handleOrgAddClose() {
            this.orgAddVisiable = false
        },
        handleOrgAddSuccess() {
            this.orgAddVisiable = false
            this.$message.success('新增机构信息成功')
            this.search()
        },
        createOrg(parent) {
            if (null == parent) {
                this.orgAddVisiable = true
                this.orgParent.id = ""
                this.orgParent.orgCode = ""
            } else if (parent.orgStatus == "03") {
                this.$message.warn('已注销的机构无法新增下属机构')
            } else {
                this.orgAddVisiable = true
                this.orgParent.id = parent.id
                this.orgParent.orgCode = parent.orgCode
            }

        },
        handleDateChange(value) {
            if (value) {
                this.queryParams.createTimeFrom = value[0]
                this.queryParams.createTimeTo = value[1]
            }
        },
        batchDelete() {
            if (!this.selectedRowKeys.length) {
                this.$message.warning('请选择需要注销的记录')
                return
            }
            let delFlag = 1;
            this.selectedRowKeys.forEach(key => {
                for (let i = 0; i < this.dataSource.length; i++) {
                    let rowData = this.dataSource[i];
                    if (rowData.id == key) {

                        if (rowData.orgStatus == "03") {
                            this.$message.warn('机构代码' + rowData.orgCode + '已注销无法再次注销')
                            delFlag = 0;
                            break;
                        }
                        if (rowData.orgStatus == "02") {
                            this.$message.warn('机构代码' + rowData.orgCode + '已停用无法注销')
                            delFlag = 0;
                            break;
                        }
                    }
                }
            });
            if (delFlag == 1) {
                let that = this
                this.$confirm({
                    title: '确定注销所选中的记录?',
                    content: '当您点击确定按钮后，这些记录将会被彻底注销，如果其包含子记录，也将一并注销！',
                    centered: true,
                    onOk() {
                        that.$delete('admin/upmporg/' + that.selectedRowKeys.join(',')).then((res) => {
                            if (res.data.status) {
                                that.$message.success('注销成功')
                                that.selectedRowKeys = []
                                that.search()
                            } else {
                                that.$message.error(res.data.message)
                            }
                        })
                    },
                    onCancel() {
                        that.selectedRowKeys = []
                    }
                })

            }
        },
        exprotExccel() {
            let { filteredInfo } = this
            this.$export('admin/upmporg/excel', {
                ...this.queryParams,
                ...filteredInfo
            })
        },
        search() {
            let { filteredInfo } = this
            this.fetch({
                ...this.queryParams,
                ...filteredInfo
            })
        },
        reset() {
            // 取消选中
            this.selectedRowKeys = []
            // 重置列过滤器规则
            this.filteredInfo = null
            // 重置查询参数
            this.queryParams = {}
            // 清空时间选择
            this.$refs.createTime.reset()

            if (!this.user.admin) {
                this.handleInstChange(this.user.instId);
            }
        },
        handleTableChange(pagination, filters, sorter) {
            // 将这两个个参数赋值给Vue data，用于后续使用
            this.filteredInfo = filters
            this.fetch({
                sortField: sorter.field,
                sortOrder: sorter.order,
                ...this.queryParams,
                ...filters
            })
        },
        fetch(params = {}) {
            this.loading = true
            this.$get('admin/upmporg', {
                ...params
            }).then((r) => {
                let data = r.data
                this.loading = false
                if (Object.is(data.rows.children, undefined)) {
                    this.dataSource = data.rows
                } else {
                    this.dataSource = data.rows.children
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>
